package jp.eisbahn.mgapi.api;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * This class becomes a base class for all model classes.
 *If you create a model class, this class must be extended.
 * @author Yoichiro Tanaka
 */
public abstract class Model {

    /** The json object to have some information. */
    private JSONObject original;

    /**
     * Initialize this instance.
     * @param newOriginal The json object to have information for each model.
     */
    protected Model(final JSONObject newOriginal) {
        super();
        original = newOriginal;
    }

    /**
     * Retrieve the property value as String.
     * @param propertyName The property name of the value you want.
     * @return The property value.
     */
    protected final String getPropertyString(final String propertyName) {
        return (String) original.get(propertyName);
    }

    /**
     * Retrieve the property value as int.
     * @param propertyName The property name of the value you want.
     * @return The property value.
     */
    protected final int getPropertyInt(final String propertyName) {
        Object value = original.get(propertyName);
        if (value == null) {
            return 0;
        } else if (value instanceof Integer) {
            return (Integer) value;
        } else {
            return Integer.parseInt((String) value);
        }
    }

    /**
     * Retrieve the property value as an array.
     * @param propertyName The property name of the value you want.
     * @return The property value.
     */
    @SuppressWarnings("unchecked")
    protected final String[] getPropertyStringArray(final String propertyName) {
        JSONArray array = (JSONArray) original.get(propertyName);
        if (array != null) {
            return (String[]) array.toArray(new String[0]);
        } else {
            return null;
        }
    }

    /**
     * Retrieve the property value as an JSONObject object.
     * @param propertyName The property name of the value you want.
     * @return The property value.
     */
    protected final JSONObject getPropertyJSONObject(
            final String propertyName) {
        return (JSONObject) original.get(propertyName);
    }

    /**
     * Retrieve the property value as a JSONArray object.
     * @param propertyName The property name of the value you want.
     * @return The property value.
     */
    protected final JSONArray getPropertyJSONArray(final String propertyName) {
        return (JSONArray) original.get(propertyName);
    }

    /**
     * Retrieve the original json object.
     * @return The json object to have some information about the model.
     */
    public final JSONObject getOriginal() {
        return original;
    }

}
